package my.app.com.taobao.forfun.getqueryresult;


import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;

public class GetValueOfQuery {
	public String getValeuOfQuery(String urlStr, String product, String start,
			String end) {
		String value = "";
		while (value.length() == 0) {
			value = this.query(urlStr, product, start, end);
		}
		return value;
	}
	
	private String query(String urlStr, String product, String start,
			String end) {
		String value = "";
		StringBuilder sb = new StringBuilder();
		product.replace("%", "");
		URL url;
		try {
			urlStr = urlStr.replace("{product}",product);
			pl(urlStr);
			url = new URL(urlStr);

			URLConnection con = url.openConnection();
			con.setDoOutput(true);
			InputStreamReader in = new InputStreamReader(con.getInputStream(),
					Charset.forName("gbk"));
			int ch = in.read();
			while (ch != -1) {
				sb.append((char) ch);
				ch = in.read();
			}
			pl(sb);
			int startIndex = sb.indexOf(start);
			String s = sb.substring(startIndex + start.length(), startIndex + + start.length() + 25);
			int endIndex = s.indexOf(end);
			pl(s);
			value = s.substring(0, endIndex);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return value;
	}
	
	public static void pl(Object o) {
		System.out.println(o);
	}
}
